#include "linuxheader.h"
#include <workflow/HttpMessage.h>
#include <workflow/HttpUtil.h>
#include <workflow/WFFacilities.h>//wait group阻塞主线程
static WFFacilities::WaitGroup waitGroup(1);//全局变量
void sigHandler (int num)
{
    waitGroup.done();
    fprintf(stderr,"wait group is done\n");
}

void callBack(WFHttpTask *httpTask)
{
//在回调函数中，可以获取任务的所有信息；

protocol::HttpRequest *req= httpTask->get_req();//请求
protocol::HttpResponse *resp = httpTask->get_resp();//响应
int state = httpTask->get_state();
int error = httpTask->get_error();
switch(state)
{
 case WFT_STATE_SYS_ERROR:
   fprintf(stderr,"system error: %s\n",strerror(error));
 break;
   case WFT_STATE_DNS_ERROR:
   fprintf(stderr,"dns error :%s\n",gai_strerror(error));
   break;
   case WFT_STATE_SUCCESS:
    break;
}
   if(state!=WFT_STATE_SUCCESS)
   {
    fprintf(stderr,"Failed\n");
    return ;
   }
  else
  {
    fprintf(stderr,"success\n");
  }
  fprintf(stderr,"request\r\n%s %s %s\r\n",req->get_method(),
                                    req->get_request_uri(),
                                      req->get_http_version());

   //使用迭代器来遍历首部字段；
   std::string name;
   std::string value;
   protocol::HttpHeaderCursor reqCursor(req);
   while (reqCursor.next(name,value))
   {
     fprintf(stderr,"%s:%s\r\n",name.c_str(),value.c_str());
   }
   fprintf(stderr,"\r\n");
}
int main()
{
  signal(SIGINT,sigHandler);
  //创建一个工厂的框架
  WFHttpTask * httpTask = WFTaskFactory::create_http_task("http://192.168.5.128:1234",10,10,callBack);
  protocol::HttpRequest *req = httpTask->get_req();
  req->add_header_pair("Accept","*/*");
  req->add_header_pair("User-Agent","myHttpTask");
  req->set_header_pair("connerction","close");
  httpTask->start();
    waitGroup.wait();
    std::cout<<"finished!\n";


}